package com.sayimo.maker.commons.wx.pay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;

import com.sayimo.framework.common.util.PropertiesUtil;
import com.sayimo.framework.exception.ServiceException;

public class Sign {
	
	/** 
	 * @author 陈培永
	 * @Title: sign
	 * @Description: 获取签名
	 * @param jsapi_ticket
	 * @param url
	 * @return Map<String,String> 
	 */ 
	public static Map<String, String> sign(String jsapi_ticket, String url) {
		Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
		
		System.out.println("拼接之后的string1为:"+string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
	}

	private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
    
    /** 
     * @author 陈培永
     * @Title: getAccessToken
     * @Description: 获取ACCESS_TOKEN
     * @throws ServiceException
     * @return String 
     */ 
    public static String getAccessToken() {
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(
				PropertiesUtil.getPropertiesVal("SAYIMO_API_URL") + "accessToken");
		String token = "";
		try {
			client.executeMethod(method);
			InputStream stream = method.getResponseBodyAsStream();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					stream, "UTF-8"));
			StringBuffer buf = new StringBuffer();
			String line;
			while (null != (line = br.readLine())) {
				buf.append(line);
			}
			token = buf.toString();
			// 释放连接
			method.releaseConnection();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return token;
	}
	
	/** 
	 * @author 陈培永
	 * @Title: getJsApiTicket
	 * @Description: 获取JSAPI_TIKET
	 * @param token
	 * @return String 
	 */ 
	public static String getJsApiTicket(String token){
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(
				PropertiesUtil.getPropertiesVal("SAYIMO_API_URL") + "ticket");

		String ticket = "";
		try {
			
			client.executeMethod(method);
			InputStream stream = method.getResponseBodyAsStream();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					stream, "UTF-8"));
			StringBuffer buf = new StringBuffer();
			String line;
			while (null != (line = br.readLine())) {
				buf.append(line);
			}
			ticket = buf.toString();
			// 释放连接
			method.releaseConnection();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return ticket;
	}
}
